package com.dwxt.mall.service;

import com.dwxt.common.base.BaseResult;
import com.dwxt.mall.dao.PayOrderMapper;
import com.dwxt.mall.dao.ProductMapper;
import com.dwxt.mall.entity.PayOrder;
import com.dwxt.mall.entity.PayOrderExample;
import com.dwxt.mall.entity.Product;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class OrderGraphService {
    @Autowired
    private PayOrderMapper payOrderMapper;

    @Autowired
    private ProductMapper productMapper;

    public BaseResult selectOrderGraph(Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        List<Map> mapList = payOrderMapper.selectSellGroupByProductId();
        PageInfo<Map> pageInfo = new PageInfo<>(mapList);
        for (Map map : mapList) {
            int productId = (int) map.get("productId");
            double count = ((Long) map.get("count")).doubleValue();
            Product product = productMapper.selectByPrimaryKey(productId);
            map.put("name", product.getName());
            map.put("price", product.getPrice());
            map.put("stock", product.getStock());
            map.put("rate", String.format("%.4f", count / (count + product.getStock())));
        }
        pageInfo.setList(mapList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult selectOrderByProductId(Integer productId, Integer pageNum, Integer pageSize) {
        if (pageNum == null) {
            pageNum = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        PageHelper.startPage(pageNum, pageSize);
        PayOrderExample example = new PayOrderExample();
        example.createCriteria().andProductIdEqualTo(productId);
        List<PayOrder> orderList = payOrderMapper.selectByExample(example);
        PageInfo<PayOrder> pageInfo = new PageInfo<>(orderList);
        return BaseResult.ok(pageInfo);
    }

    public BaseResult selectProductByKey(Integer productId) {
        return BaseResult.ok(productMapper.selectByPrimaryKey(productId));
    }
}
